package com.vinoxm.rss.redis;

import com.vinoxm.rss.model.RssTracker;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Log4j2
public class RedisConfiguration {

    @Value("${redis.rss.expireTime}")
    public void setExpire(String expireTime) {
        String[] split = expireTime.split("\\*");
        long sum = 1;
        try {
            for (String s : split) {
                int num = Integer.parseInt(s);
                sum *= num;
            }
            RedisClient.setExpire(sum);
            log.info(String.format("[Redis Configuration] Setup redis expire: %s", sum));
        } catch (NumberFormatException ignored) {
            log.info("[Redis Configuration] Setup redis expire failed, use default value!");
        }
    }

    @Autowired
    public void setupBaseRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        RedisClient.setBaseRedisTemplate(template);
    }

    @Autowired
    public void setupTrackerRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, RssTracker> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RssTracker.class));
        template.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RssTracker.class));
        template.afterPropertiesSet();
        RedisClient.setTrackerRedisTemplate(template);
    }

}
